import React, { useState, useEffect } from "react";
import { InputNumber } from "antd";
import "./index.less";

const direction = ["top", "right", "bottom", "left"];
type MarginType = [number, number, number, number];
interface IVMarginProps {
  value?: MarginType;
  defualt?: MarginType;
  onChange?: (value: MarginType) => any;
}

const VMargin: React.FC<IVMarginProps> = (props) => {
  const [value, setValue] = useState<MarginType>(props.value || props.defualt || [0, 0, 0, 0]);
  const [editing, setEditing] = useState<string>("");
  useEffect(() => {
    setValue(props.value || value);
  }, [props.value])
  const onMarginChange = (val: number, position: number) => {
    value[position] = val;
    setValue([...value]);
  }
  const changeEnter = (ev: React.KeyboardEvent<HTMLInputElement>) => {
    const { onChange } = props;
    if (ev.code === "Enter") {
      onChange && onChange(value);
      setEditing("");
    }
  }
  /* 渲染只读状态margin展示 */
  const renderReadOnlyMargin = () => {
    return <div className="read-only-wrapper">
      <div className="inside-wrapper"></div>
      {value.map((num, index) => <div className={`margin-item margin-item-${direction[index]}`} key={direction[index]}>
        {
          editing === direction[index] ? <InputNumber
            className="margin-edit"
            onChange={(val) => onMarginChange(val, index)}
            onKeyUp={changeEnter}
            defaultValue={num} /> : (<span onDoubleClick={() => setEditing( direction[index] )}>{num ? num : "-"}</span>)
        }
      </div>)}
    </div>
  }
  return <div className="v-margin-wrapper">
    { renderReadOnlyMargin() }
  </div>
}

export default VMargin;